package com.song.provider.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

/**
 * @Author 宋伟宁
 * @Date 2024/1/10
 * @Version 1.0
 **/
@Component
public class DefindException implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setStatus(429);
        String msg="";
        if(e instanceof AuthorityException){
            httpServletResponse.setStatus(403);
            msg="权限不足";
        }else if(e instanceof SystemBlockException){
            msg="系统限流";
        }else if(e instanceof FlowException){
            msg="限流异常";
        }else if(e instanceof DegradeException){
            msg="降级异常";
        }else if(e instanceof ParamFlowException){
            msg="热点异常";
        }
        PrintWriter out = httpServletResponse.getWriter();
        int status= httpServletResponse.getStatus();
        out.print("{\"code\":\""+ status + "\",\"message\":\""+msg + "\"}");
        out.flush();
        out.close();
    }
}
